package com.xoa.service.hr;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrWorkExperienceMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.hr.HrWorkExperience;
import com.xoa.model.hr.HrWorkExperienceWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zxy on 2018/7/3.
 */
@Service
public class HrWorkExperienceService {
    @Resource
    private HrWorkExperienceMapper hrWorkExperienceMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 新建工作经历
     */
    public ToJson<HrWorkExperienceWithBLOBs> addHrWorkExperience(HttpServletRequest request, HrWorkExperienceWithBLOBs hrWorkExperienceWithBLOBs) {
        ToJson<HrWorkExperienceWithBLOBs> toJson = new ToJson<HrWorkExperienceWithBLOBs>(1,"err");
        //获取当前登录人
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        try{
            String staffName = hrWorkExperienceWithBLOBs.getStaffName();
            if (staffName.contains(",")) {
                String substring = staffName.substring(0, staffName.length() - 1);
                hrWorkExperienceWithBLOBs.setStaffName(substring);
            }
            hrWorkExperienceWithBLOBs.setCreateUserId(users.getUserName());
            hrWorkExperienceWithBLOBs.setCreateDeptId(users.getDeptId());
            hrWorkExperienceWithBLOBs.setAddTime(new Date());
            hrWorkExperienceWithBLOBs.setLastUpdateTime(new Date());
            int a = hrWorkExperienceMapper.insertSelective(hrWorkExperienceWithBLOBs);
            if(a>0){
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 修改工作经历
     */
    public ToJson<HrWorkExperienceWithBLOBs> updateHrWorkExperience(HttpServletRequest request, HrWorkExperienceWithBLOBs hrWorkExperienceWithBLOBs) {
        ToJson<HrWorkExperienceWithBLOBs> toJson = new ToJson<HrWorkExperienceWithBLOBs>(1,"err");
        try{
            String staffName = hrWorkExperienceWithBLOBs.getStaffName();
            if (staffName.contains(",")) {
                String substring = staffName.substring(0, staffName.length() - 1);
                hrWorkExperienceWithBLOBs.setStaffName(substring);
            }
            hrWorkExperienceWithBLOBs.setLastUpdateTime(new Date());
            int a = hrWorkExperienceMapper.updateByPrimaryKeySelective(hrWorkExperienceWithBLOBs);
            if(a>0){
                toJson.setFlag(0);
                toJson.setMsg("修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 查询工作经历详情信息
     */
    public ToJson<HrWorkExperience> selectById(HttpServletRequest request, Integer wExperienceId) {
        ToJson<HrWorkExperience> toJson = new ToJson<HrWorkExperience>(1,"err");
        try{
            HrWorkExperienceWithBLOBs hrWorkExperienceWithBLOBs = hrWorkExperienceMapper.selectByPrimaryKey(wExperienceId);
            if(hrWorkExperienceWithBLOBs !=null){
                String username = usersMapper.getUsernameByUserId(hrWorkExperienceWithBLOBs.getStaffName());
                //附件处理
                List<Attachment> attachmentList=GetAttachmentListUtil.returnAttachment(hrWorkExperienceWithBLOBs.getAttachmentName(),hrWorkExperienceWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), "INCENTIVE");
                hrWorkExperienceWithBLOBs.setAttachmentList(attachmentList);
                if(username != null){
                    hrWorkExperienceWithBLOBs.setUserName(username);
                }else {
                    hrWorkExperienceWithBLOBs.setUserName("");
                }
                toJson.setObject(hrWorkExperienceWithBLOBs);
                toJson.setFlag(0);
                toJson.setMsg("详情查询成功");

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 删除
     */
    public ToJson<HrWorkExperience> deleteById(HttpServletRequest request, Integer[] wExperienceId) {
        ToJson<HrWorkExperience> toJson = new ToJson<HrWorkExperience>(1,"err");
        try{
//            int a = 0;
            if(wExperienceId.length == 1){
                int a = hrWorkExperienceMapper.deleteByPrimaryKey(wExperienceId[0]);
                if(a>0){
                    toJson.setFlag(0);
                    toJson.setMsg("删除成功");
                }
            }
            if(wExperienceId.length > 1){
                int a = hrWorkExperienceMapper.deleteByWexperienceId(wExperienceId);
                if(a>0){
                    toJson.setFlag(0);
                    toJson.setMsg("删除成功");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 列表导出
     */
    public ToJson<HrWorkExperienceWithBLOBs> selectList(HttpServletRequest request, HttpServletResponse response, HrWorkExperienceWithBLOBs hrWorkExperienceWithBLOBs, Integer page, Integer pageSize, boolean useFlag, String export) {
        ToJson<HrWorkExperienceWithBLOBs> toJson = new ToJson<HrWorkExperienceWithBLOBs>(1,"err");
        try{
            if(export==null){
                export="0";
            }
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            HashMap<String,Object> map = new HashMap();
//            String staffName = hrWorkExperienceWithBLOBs.getStaffName();
            map.put("postOfJob",hrWorkExperienceWithBLOBs.getPostOfJob());
            map.put("workUnit",hrWorkExperienceWithBLOBs.getWorkUnit());
            map.put("mobile",hrWorkExperienceWithBLOBs.getMobile());
            map.put("workContent",hrWorkExperienceWithBLOBs.getWorkContent());
            map.put("keyPerformance",hrWorkExperienceWithBLOBs.getKeyPerformance());
            map.put("pageParams", pageParams);
            List<HrWorkExperienceWithBLOBs> list = null;
            if (hrWorkExperienceWithBLOBs.getStaffName()!=null&& hrWorkExperienceWithBLOBs.getStaffName()!=""){
                //判断用户是否为空并转化字符串
                if(!StringUtils.checkNull(hrWorkExperienceWithBLOBs.getStaffName().toString())){
                    String fromIds = hrWorkExperienceWithBLOBs.getStaffName().toString();
                    String[] substring = fromIds.split(",");//分割
                    map.put("staffName",substring);
                }
            }
            list = hrWorkExperienceMapper.selectList(map);

            if(list != null){
                if (list.size() > 0) {
                    for (HrWorkExperienceWithBLOBs le : list) {
                        List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(le.getAttachmentName(), le.getAttachmentId(), "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.WORKEXPERIENCE);
                        le.setAttachmentList(attachments);
                        SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        le.setStartDateArr(format0.format(le.getStartDate()));
                        le.setEndDateArr(format0.format(le.getEndDate()));
                    }
                }
            }
            toJson.setObj(list);
            toJson.setTotleNum(hrWorkExperienceMapper.selectCount());
            toJson.setMsg("列表查询成功");
            toJson.setFlag(0);
            if(export.equals("1")) {
                OutputStream out = response.getOutputStream();
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("工作经历信息", 12);
                String[] secondTitles = {"单位员工", "工作单位", "开始日期", "结束日期", "行业类别", "所在部门", "担任职务", "证明人", "工作内容", "主要业绩", "离职原因", "备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"userName", "workUnit", "startDateArr", "endDateArr", "mobile", "workBranch", "postOfJob","witness","workContent", "keyPerformance","reasonForLeaving","remark"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                String filename = "工作经历信息表.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
    /**
     * @作者 zxy
     * @创建日期 2018/7/3
     * @方法说明 导入
     */
    public ToJson<HrWorkExperience> importWorkExperience(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<HrWorkExperience> json = new ToJson<HrWorkExperience>(1,"error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            StringBuffer buffer=new StringBuffer();
            if(osName.toLowerCase().startsWith("win")){
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if(uploadPath.indexOf(":")==-1){
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if(basePath.indexOf("/xoa")!=-1){
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2=basePath.substring(0,index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
                buffer=buffer.append(rb.getString("upload.win"));
            }else{
                path=path.append(rb.getString("upload.linux"));
                buffer=buffer.append(rb.getString("upload.linux"));
            }
            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrWorkExperienceWithBLOBs hrWorkExperience = null;
                    for (int i = 3; i <= lastRowNum; i++) {
                        hrWorkExperience = new HrWorkExperienceWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 用户名
                                            Users users = usersMapper.getUserByUserName(cell.getStringCellValue());
                                            if (users!=null){
                                                Department department = departmentMapper.getDeptById(users.getDeptId());
                                                hrWorkExperience.setCreateDeptId(department.getDeptId());
                                            }
                                            hrWorkExperience.setCreateUserId(cell.getStringCellValue());

                                            break;
                                        case 1:
                                            // 单位员工
                                            if (cell.getStringCellValue() != null) {
                                                Users user = usersMapper.getUserByUserName(cell.getStringCellValue());
                                                if (user!=null){
                                                    hrWorkExperience.setStaffName(user.getUserId());
                                                }
                                            }
                                            break;
                                        case 2:
                                            //担任职务
                                            hrWorkExperience.setPostOfJob(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //所在部门
                                            hrWorkExperience.setWorkBranch(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //证明人
                                            hrWorkExperience.setWitness(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            // 开始日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrWorkExperience.setStartDate(date);
                                                break;
                                            }
                                            hrWorkExperience.setStartDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 6:
                                            // 结束日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrWorkExperience.setEndDate(date);
                                                break;
                                            }
                                            hrWorkExperience.setEndDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 7:
                                            // 行业类别
                                            hrWorkExperience.setMobile(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //工作单位
                                            hrWorkExperience.setWorkUnit(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            // 工作内容
                                            hrWorkExperience.setWorkContent(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            // 离职原因
                                            hrWorkExperience.setReasonForLeaving(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            // 备注
                                            hrWorkExperience.setRemark(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            // 主要业绩
                                            hrWorkExperience.setKeyPerformance(cell.getStringCellValue());
                                            break;
                                    }

                                }
                            }
                            if(hrWorkExperience!=null){
                                hrWorkExperience.setAddTime(new Date());
                                hrWorkExperience.setLastUpdateTime(new Date());
                                int a =hrWorkExperienceMapper.insertSelective(hrWorkExperience);
                                if (a!=0){
                                    success = success + 1;
                                }
                            }

                        }
                    }
                    HrWorkExperienceWithBLOBs temp=new HrWorkExperienceWithBLOBs();
                    json.setFlag(0);
                    json.setMsg("ok");
                    json.setObject(temp);
                }else {
                    json.setMsg("数据保存异常");
                    json.setFlag(1);
                }

            }
          /*  HrWorkExperienceWithBLOBs temp=new HrWorkExperienceWithBLOBs();
            temp.setCount(success);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(temp);*/
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        }
        return json;
    }


    /**
     * @作者 qizhongxiao
     * @创建日期 2018/7/31
     * @方法说明 人事分析查数量
     */
    public ToJson<HrWorkExperience> selectNumByCon(HrWorkExperience record, Integer[] deptId) {
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrWorkExperience> list = hrWorkExperienceMapper.selectNumByCon(map);

            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 李阳
     * 根据 staffName 查找工作经历
     * @param staffName
     * @return
     */
    public ToJson<HrWorkExperienceWithBLOBs> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag){
        ToJson<HrWorkExperienceWithBLOBs> json = new ToJson<HrWorkExperienceWithBLOBs>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);

        try{
            List<HrWorkExperienceWithBLOBs> list=null;
            if(!staffName.isEmpty()){
                String[] str=staffName.split(",");
                map.put("staffName",str);
                list =hrWorkExperienceMapper.getByStaffName(map);
            }
            if(list.size()>0){
                for(HrWorkExperienceWithBLOBs work:list){
                    if(work.getStaffName()!=null){
                        Users user = usersMapper.findUsersByuserId(work.getStaffName()); //根据 id 找名字
                        work.setStaffName(user.getUserName());
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(hrWorkExperienceMapper.getByStaffNameCount(staffName));
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }


    //查询全部人的岗位
    public ToJson<HrWorkExperience> selectNumPost(HrWorkExperience record) {
        ToJson toJson=new ToJson(1,"暂无信息");
        try {
            List<Map<String,Object>> list =hrWorkExperienceMapper.selectNumPost();
            if (list.size()>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
                toJson.setObj(list);
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }
}
